package gob.osinerg.emergencia.dao;

import gob.osinerg.emergencia.bean.AccidenteGraveFinalTestigo;
import gob.osinerg.emergencia.bean.FormularioEmergenciaUnmay;
import gob.osinerg.emergencia.bean.SiniestroPreliminar;
import gob.osinerg.emergencia.bean.SiniestroPreliminarAccidentado;
import gob.osinerg.emergencia.bean.TipoSiniestro;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class SiniestroPreliminarDAOImpl extends GenericDAOImpl implements SiniestroPreliminarDAO{

	public void save(SiniestroPreliminar bean, FormularioEmergenciaUnmay beanform) throws Exception {
		Session session = getSession();
		Transaction transaction = null;
		SiniestroPreliminarAccidentado accdntdo = null;
		try {
			transaction = session.beginTransaction();
			if(beanform.getId() == null){
				beanform.setId(getNextPK("FRM_EMR_UM_SEQ"));
			}

			if(bean.getId() == null){
				bean.setId(getNextPK("SINIE_PRE_SEQ"));
			}
			
			if(beanform.getNmroEmrgncia() == null){
				beanform.setNmroEmrgncia(bean.getIdFormato());
			}
			
			beanform.setFlagTemporal("NO");
			
			session.saveOrUpdate(beanform);
			bean.setIdFormularioEmergencia(beanform.getId());
			session.saveOrUpdate(bean);
			
			for(int i=0;i < bean.getListaAccidentado().size();i++){
				accdntdo = (SiniestroPreliminarAccidentado)bean.getListaAccidentado().get(i);
				accdntdo.setId(getNextPK("SNSTRO_PRLMNAR_ACCDNTDOS_SEQ"));
				accdntdo.setIdFormularioEmergencia(bean.getId());
				session.saveOrUpdate(accdntdo);
			}			
			
			
			transaction.commit();
		} catch (Exception e) {
			transaction.rollback();
			throw e;
		}finally{
			session.close();
		}
	}
	
	// 1 = OK | 0 = error
	public int save(SiniestroPreliminar bean, FormularioEmergenciaUnmay beanform, boolean opcion) throws Exception {
		Session session = getSession();
		Transaction transaction = null;
		SiniestroPreliminarAccidentado accdntdo = null;
		int resultado = 0;
		try {
			transaction = session.beginTransaction();
			if(beanform.getId() == null){
				beanform.setId(getNextPK("FRM_EMR_UM_SEQ"));
			}

			if(bean.getId() == null){
				bean.setId(getNextPK("SINIE_PRE_SEQ"));
			}
			
			if(beanform.getNmroEmrgncia() == null){
				beanform.setNmroEmrgncia(bean.getIdFormato());
			}
			
			session.saveOrUpdate(beanform);
			bean.setIdFormularioEmergencia(beanform.getId());
			session.saveOrUpdate(bean);
			
			for(int i=0;i < bean.getListaAccidentado().size();i++){
				accdntdo = (SiniestroPreliminarAccidentado)bean.getListaAccidentado().get(i);
				accdntdo.setId(getNextPK("SNSTRO_PRLMNAR_ACCDNTDOS_SEQ"));
				accdntdo.setIdFormularioEmergencia(bean.getId());
				session.saveOrUpdate(accdntdo);
			}			
			
			
			transaction.commit();
			resultado = 1;
		} catch (Exception e) {
			resultado = 0;
			transaction.rollback();
			throw e;
		}finally{
			session.close();
		}
		return resultado;
	}
	
	public Long getNextPK(String sequence) throws Exception {
        long result = 1;

        StringBuffer sql = new StringBuffer("");
        sql.append("SELECT ");
        sql.append(sequence);
        sql.append(".NEXTVAL AS ID FROM DUAL");        
        
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = getSession().connection().prepareStatement(sql.toString());
            rs = pstmt.executeQuery();
            if(rs.next()) {
                result = rs.getLong(1);
            }
            pstmt.close();
            pstmt = null;
            rs.close();
            rs = null;
        }
        catch(Exception e) {
            log.error(e.getMessage());
            if(pstmt != null) {
                try {pstmt.close();} catch(Exception ignore) {}
            }
            if(rs != null) {
            	try {rs.close();}catch(Exception ignore) {}
            }
        }
        return new Long(result);
    }
	
	
	public List listarTipoSiniestro() throws Exception {
        List lista = new ArrayList();
        TipoSiniestro tipoSiniestro = null;

        StringBuffer sql = new StringBuffer("");
        sql.append(" SELECT " +
        		   " NSFH_IDSEQ, RV_MEANING " +
        		   " FROM CG_REF_CODES " +
        		   " WHERE RV_DOMAIN = 'FRMTO_DOS_TPO_SNSTRO' " +
        		   " ORDER BY RV_DOMAIN ASC ");        
        
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = getSession().connection().prepareStatement(sql.toString());
            rs = pstmt.executeQuery();
            while(rs.next()) {
            	tipoSiniestro = new TipoSiniestro();
            	tipoSiniestro.setIdSiniestro(new Long(rs.getLong(1)));
            	tipoSiniestro.setDescripcion(rs.getString(2));
            	lista.add(tipoSiniestro);
            }
            pstmt.close();
            pstmt = null;
            rs.close();
            rs = null;
        }
        catch(Exception e) {
            log.error(e.getMessage());
            if(pstmt != null) {
                try {pstmt.close();} catch(Exception ignore) {}
            }
            if(rs != null) {
            	try {rs.close();}catch(Exception ignore) {}
            }
        }
        
        return lista;
    }

	

} 